﻿#region Copyright (c) 2013-05, Olaf Kober <amarok.projects@gmail.com>
//================================================================================
//	Permission is hereby granted, free of charge, to any person obtaining a copy
//	of this software and associated documentation files (the "Software"), to deal
//	in the Software without restriction, including without limitation the rights
//	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//	copies of the Software, and to permit persons to whom the Software is
//	furnished to do so, subject to the following conditions:
//
//	The above copyright notice and this permission notice shall be included in
//	all copies or substantial portions of the Software.
//
//	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//	THE SOFTWARE.
//================================================================================
#endregion

#if NET4

using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Threading;


namespace Amarok.Presentation
{
	/// <summary>
	/// </summary>
	internal static class DispatcherExtensions
	{
		#region T Invoke(Func<T>)

		/// <summary>
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="dispatcher"></param>
		/// <param name="callback"></param>
		/// <returns></returns>
		public static T Invoke<T>(
			this Dispatcher dispatcher,
			Func<T> callback)
		{
			return DispatcherExtensions.Invoke<T>(
				dispatcher,
				callback,
				DispatcherPriority.Send,
				CancellationToken.None);
		}

		#endregion

		#region T Invoke(Func<T>, DispatcherPriority)

		/// <summary>
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="dispatcher"></param>
		/// <param name="callback"></param>
		/// <param name="priority"></param>
		/// <returns></returns>
		public static T Invoke<T>(
			this Dispatcher dispatcher,
			Func<T> callback,
			DispatcherPriority priority)
		{
			return DispatcherExtensions.Invoke<T>(
				dispatcher,
				callback,
				priority,
				CancellationToken.None);
		}

		#endregion

		#region T Invoke(Func<T>, DispatcherPriority, CancellationToken)

		/// <summary>
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="dispatcher"></param>
		/// <param name="callback"></param>
		/// <param name="priority"></param>
		/// <param name="cancellationToken"></param>
		/// <returns></returns>
		public static T Invoke<T>(
			this Dispatcher dispatcher,
			Func<T> callback,
			DispatcherPriority priority,
			CancellationToken cancellationToken)
		{
			Verify.NotNull(callback, "callback");

			T result = default(T);

			if (cancellationToken.IsCancellationRequested)
				return result;

			dispatcher.Invoke(new Action(() =>
				{
					result = callback();
				}),
				priority);

			return result;
		}

		#endregion


		#region Task InvokeAsync(Action)

		/// <summary>
		/// </summary>
		/// <param name="dispatcher"></param>
		/// <param name="callback"></param>
		/// <returns></returns>
		public static Task InvokeAsync(
			this Dispatcher dispatcher,
			Action callback)
		{
			return DispatcherExtensions.InvokeAsync(
				dispatcher,
				callback,
				DispatcherPriority.Send,
				CancellationToken.None);
		}

		#endregion

		#region Task InvokeAsync(Action, DispatcherPriority)

		/// <summary>
		/// </summary>
		/// <param name="dispatcher"></param>
		/// <param name="callback"></param>
		/// <param name="priority"></param>
		/// <returns></returns>
		public static Task InvokeAsync(
			this Dispatcher dispatcher,
			Action callback,
			DispatcherPriority priority)
		{
			return DispatcherExtensions.InvokeAsync(
				dispatcher,
				callback,
				priority,
				CancellationToken.None);
		}

		#endregion

		#region Task InvokeAsync(Action, DispatcherPriority, CancellationToken)

		/// <summary>
		/// </summary>
		/// <param name="dispatcher"></param>
		/// <param name="callback"></param>
		/// <param name="priority"></param>
		/// <param name="cancellationToken"></param>
		/// <returns></returns>
		public static Task InvokeAsync(
			this Dispatcher dispatcher,
			Action callback,
			DispatcherPriority priority,
			CancellationToken cancellationToken)
		{
			var completionSource = new TaskCompletionSource<None>();

			if (cancellationToken.IsCancellationRequested)
				return TaskHelper.Canceled;

			var operation = dispatcher.BeginInvoke(
				new Action(() =>
				{
					try
					{
						callback();
						completionSource.TrySetResult(None.Instance);
					}
					catch (Exception exception)
					{
						completionSource.TrySetException(exception);
					}
				}),
				priority);

			if (cancellationToken.CanBeCanceled)
			{
				var registration = cancellationToken.Register(() =>
					{
						operation.Abort();
						completionSource.TrySetCanceled();
					});

				operation.Completed += (sender, e) => registration.Dispose();
				operation.Aborted += (sender, e) => registration.Dispose();
			}

			return completionSource.Task;
		}

		#endregion


		#region Task<T> InvokeAsync(Func<T>)

		/// <summary>
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="dispatcher"></param>
		/// <param name="callback"></param>
		/// <returns></returns>
		public static Task<T> InvokeAsync<T>(
			this Dispatcher dispatcher,
			Func<T> callback)
		{
			return DispatcherExtensions.InvokeAsync<T>(
				dispatcher,
				callback,
				DispatcherPriority.Send,
				CancellationToken.None);
		}

		#endregion

		#region Task<T> InvokeAsync(Func<T>, DispatcherPriority)

		/// <summary>
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="dispatcher"></param>
		/// <param name="callback"></param>
		/// <param name="priority"></param>
		/// <returns></returns>
		public static Task<T> InvokeAsync<T>(
			this Dispatcher dispatcher,
			Func<T> callback,
			DispatcherPriority priority)
		{
			return DispatcherExtensions.InvokeAsync<T>(
				dispatcher,
				callback,
				priority,
				CancellationToken.None);
		}

		#endregion

		#region Task<T> InvokeAsync(Func<T>, DispatcherPriority, CancellationToken)

		public static Task<T> InvokeAsync<T>(
			this Dispatcher dispatcher,
			Func<T> callback,
			DispatcherPriority priority,
			CancellationToken cancellationToken)
		{
			var completionSource = new TaskCompletionSource<T>();

			if (cancellationToken.IsCancellationRequested)
				return TaskHelper.FromResult<T>(default(T));

			var operation = dispatcher.BeginInvoke(
				new Action(() =>
				{
					try
					{
						var result = callback();
						completionSource.TrySetResult(result);
					}
					catch (Exception exception)
					{
						completionSource.TrySetException(exception);
					}
				}),
				priority);

			if (cancellationToken.CanBeCanceled)
			{
				var registration = cancellationToken.Register(() =>
				{
					operation.Abort();
					completionSource.TrySetCanceled();
				});

				operation.Completed += (sender, e) => registration.Dispose();
				operation.Aborted += (sender, e) => registration.Dispose();
			}

			return completionSource.Task;
		}

		#endregion

	}
}

#endif
